package com.gitee.cui.basic.use;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

/**
 * 测试线程的interrupt
 */
@Slf4j
public class Interrupt {

    /**
     * 睡眠时长
     */
    public static final int SLEEP_GAP = 5000;
    /**
     * 睡眠次数
     */
    public static final int MAX_TURN = 50;

    static class SleepThread extends Thread {
        static int threadSeqNumber = 1;

        public SleepThread() {
            super("sleepThread-" + threadSeqNumber);
            threadSeqNumber++;
        }

        public void run() {
            try {
                log.info(getName() + " 进入睡眠.");
                // 线程睡眠一会
                Thread.sleep(SLEEP_GAP);
            } catch (InterruptedException e) {
                e.printStackTrace();
               log.info(getName() + " 发生被异常打断.");
                return;
            }
           log.info(getName() + " 运行结束.");
        }

    }

    public static void main(String args[]) throws InterruptedException {

        Thread thread1 = new SleepThread();
        thread1.start();
        Thread thread2 = new SleepThread();
        thread2.start();
        // 等待2秒
        ThreadUtil.sleepSeconds(2);
        // 打断线程1
        thread1.interrupt();
        // 等待5秒
        ThreadUtil.sleepSeconds(5);
        // 打断线程2，此时线程2已经终止
        thread2.interrupt();
        // 等待1秒
        ThreadUtil.sleepSeconds(1);
        log.info("程序运行结束.");
    }

    //测试用例：获取异步调用的结果
    @Test
    public void testInterrupted2() {
        Thread thread = new Thread() {
            public void run() {
                log.info("线程启动了");
                // 一直循环
                while (true) {
                    log.info("isInterrupted(): {}", isInterrupted());
                    ThreadUtil.sleepMilliSeconds(SLEEP_GAP);

                    // 如果调用 interrupt 为true，退出死循环
                    if (isInterrupted()) {
                        log.info("线程结束了");
                        return;
                    }
                }
            }
        };
        thread.start();
        // 等待2秒
        ThreadUtil.sleepSeconds(2);
        // 打断线程
        thread.interrupt();
        // 等待2秒
        ThreadUtil.sleepSeconds(2);
        thread.interrupt();
    }
}